#!/usr/bin/python
# -*- coding: cp1250 -*-

import datetime
import decimal
import re
import string
import time

D = decimal.Decimal

def byDateTime(inA_s, inB_s, verbose=0):

    dtTupleA = time.strptime(inA_s, "%Y-%m-%d %H:%M:%S")
    dtTupleB = time.strptime(inB_s, "%Y-%m-%d %H:%M:%S")
    # for "03/06/05 11:22:00AM" use "%m/%d/%y %I:%M:%S%p"

    # mktime() gives seconds since epoch 1/1/1970 00:00:00
    time_difference = time.mktime(dtTupleB) - time.mktime(dtTupleA)
    if verbose == 1 :
        print '\n'+str(dtTupleA)+'\n'+str(dtTupleB)
        # eg. (2005, 3, 6, 11, 22, 0, 5, 91, -1)
        print "Time difference = %d seconds"        % int(time_difference)
        print "Time difference = %0.1f minutes"     % (time_difference/60.0)
        print "Time difference = %0.2f hours"       % (time_difference/(60.0*60))
        print "Time difference = %0.2f days"        % (time_difference/(60.0*60*24))

    diffDays_n = time_difference/(60.0*60*24)
    return re.sub('\.0','', str(    round(diffDays_n,2)    ))


def date_time_diff_seconds(a_dtime, b_dtime, verbose=0):

    dtTupleA = time.strptime(a_dtime, "%Y-%m-%d %H:%M:%S")
    dtTupleB = time.strptime(b_dtime, "%Y-%m-%d %H:%M:%S")
    # for "03/06/05 11:22:00AM" use "%m/%d/%y %I:%M:%S%p"

    # mktime() gives seconds since epoch 1/1/1970 00:00:00
    time_difference = time.mktime(dtTupleB) - time.mktime(dtTupleA)
    if verbose == 1 :
        print '\n'+str(dtTupleA)+'\n'+str(dtTupleB)
        # eg. (2005, 3, 6, 11, 22, 0, 5, 91, -1)
        print "Time difference = %d seconds"        % int(time_difference)
        print "Time difference = %0.1f minutes"     % (time_difference/60.0)
        print "Time difference = %0.2f hours"       % (time_difference/(60.0*60))
        print "Time difference = %0.2f days"        % (time_difference/(60.0*60*24))

    return int(time_difference)

def byDate(adate, bdate, verbose=0):
    '''
    >>> byDate("2007-03-04","2007-03-7")
    3
    '''
    atuple = (int(adate[:4]), int(adate[5:7]), int(adate[8:10]), 0, 0, 0, 0, 0, -1)
    btuple = (int(bdate[:4]), int(bdate[5:7]), int(bdate[8:10]), 0, 0, 0, 0, 0, -1)

    # 16.09.2010 This is a 'before 1970' patch
    # if date is older than 1970 following steps are made:
    #  1. SHIFT = the diffrence between 1970 and the year in the date in days*
    #  2. Year in date is replaced by 1970
    #  3. On the end the SHIFT value is added to the result
    # * patch is approximate and not unlimited because shift in days is counted as
    # years times 365.24219 (length of tropical year) so it can differ by one day for
    # short intervals and a lot of days for long intervals because of history - see
    # (http://cs.wikipedia.org/wiki/Gregori%C3%A1nsk%C3%BD_kalend%C3%A1%C5%99 for example
    # the section about 1582-10-04 to 1582-10-15). Nevertheless still enough accurate for
    # our needs.
    shiftAdate = 0
    shiftBdate = 0
    if atuple[0] < 1970:
        shiftAdate = (atuple[0] - 1970) * 365.24219 * 24 * 60 * 60
        atuple = (1970, int(adate[5:7]), int(adate[8:10]), 0, 0, 0, 0, 0, -1)
    if btuple[0] < 1970:
        shiftBdate = (btuple[0] - 1970) * 365.24219 * 24 * 60 * 60
        btuple = (1970, int(bdate[5:7]), int(bdate[8:10]), 0, 0, 0, 0, 0, -1)
    
    #atuple = time.strptime(inA_s + " 00:00:00", "%Y-%m-%d %H:%M:%S")
    #btuple = time.strptime(inB_s + " 00:00:00", "%Y-%m-%d %H:%M:%S")
    # for "03/06/05 11:22:00AM" use "%m/%d/%y %I:%M:%S%p"

    # mktime() gives seconds since epoch 1/1/1970 00:00:00
    time_difference = (time.mktime(btuple) + shiftBdate) - (time.mktime(atuple) + shiftAdate)
    if verbose == 1 :
        print '\n'+str(dtTupleA)+'\n'+str(dtTupleB)
        # eg. (2005, 3, 6, 11, 22, 0, 5, 91, -1)
        print "Time difference = %d seconds"        % int(time_difference)
        print "Time difference = %0.1f minutes"     % (time_difference/60)
        print "Time difference = %0.2f hours"       % (time_difference/(60*60))
        print "Time difference = %0.2f days"        % (int(time_difference)/(60*60*24))

    return int(time_difference)/(60*60*24)

def byTime(inA_s, inB_s):
    if inA_s == '' or inB_s == '':
        return ''
    else:
        if len(inA_s) == 5:
            inA2_s = '2000-01-01 '+inA_s+':00'
            inB2_s = '2000-01-01 '+inB_s+':00'
        else:
            inA2_s = inA_s
            inB2_s = inB_s

        timeTuple1 = time.strptime(inA2_s, "%Y-%m-%d %H:%M:%S")
        timeTuple2 = time.strptime(inB2_s, "%Y-%m-%d %H:%M:%S")
        #print timeTuple2 # test eg. (2005, 3, 6, 11, 22, 0, 5, 91, -1)

        # mktime() gives seconds since epoch 1/1/1970 00:00:00
        result_n = (time.mktime(timeTuple2) - time.mktime(timeTuple1))/(60*60)
        # for cases like ..... print time_diff_iso("22:00","05:33") .... 7.55
        if int(result_n) < 0 and len(inA_s) == 5: result_n = 24 + D(str(result_n))
        return result_n
        #return re.sub('\.0','', str(    round(diffDays_n,0)    ))

def byDateNow(iso_d):
    """ from/to now """
    now = datetime.date.today()
    ind = datetime.date(int(iso_d[:4]),
                        int(iso_d[5:7]),
                        int(iso_d[8:10]))
    # int(string.split(iso_d[11:1],'-')
    return (now - ind)

def yearsMonthsDays(days):
    '''
    >>> yearsMonthsDays(byDate("2006-11-01","2009-06-17"))
    Days: 958  =  years: 2  months: 7  days: 18
    '''
    print 'Days:', days,

    years = int(days/365)
    days_lessthanyear = days%365
    months = int(days_lessthanyear/30)
    days_lessthanmonth = days_lessthanyear%30

    print ' =  years:', years,
    print ' months:', months,
    print ' days:', days_lessthanmonth

def main():

    yearsMonthsDays(byDate("2006-11-01","2009-06-17"))
    
    print """byDateTime("2007-03-04 13:00:00","2007-03-07 23:33:00")""",
    print byDateTime("2007-03-04 13:00:00","2007-03-07 23:33:00")
    print """byDate("1939-09-01","1945-05-08")""",
    print byDate("1939-09-01","1945-05-08")
    print """byDate("2007-03-04","2007-03-07")""",
    print byDate("2007-03-04","2007-03-07")
    print """byTime("13:00","23:33")""",
    print byTime("13:00","23:33")

    print """byDateTime("2007-03-04 22:00:00","2007-03-04 05:33:00")""",
    print byDateTime("2007-03-04 22:00:00","2007-03-04 05:33:00")
    print """byDate("2007-03-04","2007-03-04")""",
    print byDate("2007-03-04","2007-03-04")
    print """byTime("22:00","05:33")""",
    print byTime("22:00","05:33")

    print byDateNow("2007-03-03")

    print """ date_time_diff_seconds("2007-03-04 13:00:00","2007-03-04 13:01:00")""",
    print date_time_diff_seconds("2007-03-04 13:00:00","2007-03-04 13:01:00")
    
    print """ date_time_diff_seconds("2007-03-04 13:00:00","2007-03-04 12:59:00")""",
    print date_time_diff_seconds("2007-03-04 13:00:00","2007-03-04 12:59:00")
    
if __name__ == "__main__":
    main()

    import doctest
    doctest.testmod()
